"use strict";
const co = require("co");
const Seneca = require('seneca');
const seneca = Seneca().use('seneca-as-promised');
const cp = require('child_process');

function exec(cmd) {
    return new Promise((resolve, reject) => {
        cp.exec(cmd, function(e, stdout, stderr) {
            if (e) {
                reject(e);
            }
            resolve({
                stderr: stderr,
                stdout: stdout
            });
        });
    });
}

require("./enhance");
const server = require("./server.js");

// curl -d '{"role":"admin","cmd":"stop"}' http://localhost:11001/act
seneca.use(function() {
    this.add({
        role: "admin",
        cmd: "start"
    }, function(msg, done) {
        server.startWebSocket().then(() => {
            done(null, "started");
        });
    });

    this.add({
        role: "admin",
        cmd: "stop"
    }, function(msg, done) {
        server.stopWebSocket().then(() => {
            done(null, "stoped");
        });
    });
    this.add({
        role: "admin",
        cmd: "test"
    }, function(msg, done) {
        done(null, "test");
    });
}).listen({
    type: 'http',
    port: 11001
});

co(function*() {
    const devStatus = process.env.devStatus;
    if (devStatus==null) {
        throw "devStatus没有指定";
    }
    let s = yield exec("ufw enable");
    console.log(s);
    s = yield exec("ufw default allow");
    console.log(s);
    yield server.startServer(devStatus);
}).catch((err) => {
    console.log(err);
});
process.on('uncaughtException', (err) => {
    console.log(err);
});
